﻿using AspNetCoreRateLimit;
using AspNetCoreRateLimit.Redis;
using Forum.Model;
using StackExchange.Redis;

namespace Forum.StaticClass
{
    public static class ConfigureRateLimit
    {
        public static void AddRateLimit(this IServiceCollection services, IConfiguration conf)
        {
            //services.AddMemoryCache();
            ////services.Configure<IpRateLimitPolicies>(conf.GetSection("IpRateLimitPolicies"));
            //services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
            //services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
            //services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
            //services.AddSingleton<IProcessingStrategy, AsyncKeyLockProcessingStrategy>();

            services.Configure<IpRateLimitOptions>(conf.GetSection("IpRateLimiting"));
            var redisOptions = ConfigurationOptions.Parse(SecretConfig.RedisConnectionString);
            services.AddSingleton<IConnectionMultiplexer>(provider => ConnectionMultiplexer.Connect(redisOptions));
            services.AddRedisRateLimiting();
            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        }

        public static IApplicationBuilder UseRateLimit(this IApplicationBuilder app)
        {
            app.UseIpRateLimiting();

            return app;
        }
    }
}
